#include "USART.h"

void UART_Init(void){
	  RCC_APB2PeriphClockCmd(RCC_APB2Periph_USART1,ENABLE);
	
	  GPIO_InitTypeDef GPIO_InitStructure;
	  GPIO_InitStructure.GPIO_Pin = GPIO_Pin_9|GPIO_Pin_10;
	  GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
	  GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF;
	  GPIO_InitStructure.GPIO_PuPd = GPIO_PuPd_UP;
	  GPIO_Init(GPIOA, &GPIO_InitStructure);
	  GPIO_PinAFConfig(GPIOA,GPIO_PinSource9,GPIO_AF_USART1);
	  GPIO_PinAFConfig(GPIOA,GPIO_PinSource10,GPIO_AF_USART1);

	
	  USART_InitTypeDef USART_InitStruct;
	  USART_StructInit(&USART_InitStruct);
	  USART_InitStruct.USART_BaudRate = 921600;
	  USART_Init(USART1,&USART_InitStruct);

	  USART_ITConfig(USART1,USART_IT_RXNE,ENABLE);

	  NVIC_InitTypeDef NVIC_InitStruct;
	  NVIC_InitStruct.NVIC_IRQChannel = USART1_IRQn;
	  NVIC_InitStruct.NVIC_IRQChannelCmd = ENABLE;
	  NVIC_InitStruct.NVIC_IRQChannelPreemptionPriority = 0;
	  NVIC_InitStruct.NVIC_IRQChannelSubPriority = 1;
	  NVIC_Init(&NVIC_InitStruct);

	  USART_ClearITPendingBit(USART1,USART_IT_RXNE);
	  USART_Cmd(USART1,ENABLE);
}

// rewrite to UART
int fputc(int ch, FILE *p){
	USART1->DR = ch;
	while(USART_GetFlagStatus(USART1,USART_FLAG_TXE)==RESET);
	return ch;
}


void USART1_IRQHandler(){
	uint8_t rx_tmp;
	if(USART_GetITStatus(USART1,USART_IT_RXNE)!=RESET){
		//USART_ClearITPendingBit(USART1,USART_IT_RXNE);
		rx_tmp = USART1->DR;
		Ymodem_RecvHandler(&rx_tmp);
	}
}
